﻿Imports System.Text.RegularExpressions
Imports Q7P1TTS.Lib
Imports ComponentFactory.Krypton
Imports ComponentFactory.Krypton.Navigator
Imports ComponentFactory.Krypton.Toolkit


Public Class CustomerForm

    Dim cust As Customer
    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        cust = New Customer()
    End Sub

    Public Sub New(ByVal ID As Integer)
        InitializeComponent()
        cust = CustomerController.load(ID)
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        If validateData() Then
            ' Insert customer
            cust.Email = txtEmail.Text.Trim()
            If cust.Password <> txtPassword.Text.Trim() Then
                cust.Password = ConvertHelper.ToMD5(txtPassword.Text.Trim())
            End If

            cust.FirstName = txtFirstName.Text.Trim()
            cust.LastName = txtLastName.Text.Trim()
            cust.Address = txtAddress.Text.Trim()
            cust.City = txtCity.Text.Trim()
            cust.State = txtState.Text.Trim()
            cust.Zip = txtZip.Text.Trim()
            cust.Phone = txtPhone.Text.Trim()
            If String.IsNullOrEmpty(cust.Account) Then
                cust.Account = ConvertHelper.GenerateAccount("CUST")
            End If

            If CustomerController.save(cust) > 0 Then
                Dim mainForm As MainForm = Me.FindForm()
                If mainForm.isAdmin Then
                    mainForm.GoToForm(New CustomerList())
                Else
                    If MessageBox.Show("Thank you! Your account has been generated successfully. Please write it down. " & ControlChars.NewLine & "Account: " & cust.Account & ControlChars.NewLine & "Password: " & txtPassword.Text.Trim(), "Register Successfully!!") = DialogResult.OK Then
                        mainForm.GoToForm(New Welcome(), "Welcome")
                        Dim loginForm As New LoginForm()
                        loginForm.ShowDialog(Me)
                    End If
                End If
            Else
                MessageBox.Show("Sorry! There was an error while generating account. Please try again later.", "Register Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

            End If
    End Sub

    Private Function validateData() As Boolean
        Dim res As Boolean = True
        ' validate empty data
        If String.IsNullOrEmpty(txtEmail.Text.Trim()) Then
            errorProvider.SetError(txtEmail, "Email can not be left blank!")
            res = res And False
        Else
            errorProvider.SetError(txtEmail, "")
        End If
        If String.IsNullOrEmpty(txtPassword.Text.Trim()) Then
            errorProvider.SetError(txtPassword, "Password can not be left blank!")
            res = res And False
        Else
            errorProvider.SetError(txtPassword, "")
        End If
        If String.IsNullOrEmpty(txtFirstName.Text.Trim()) Then
            errorProvider.SetError(txtFirstName, "First Name can not be left blank!")
            res = res And False
        Else
            errorProvider.SetError(txtFirstName, "")
        End If
        If String.IsNullOrEmpty(txtLastName.Text.Trim()) Then
            errorProvider.SetError(txtLastName, "Last Name can not be left blank!")
            res = res And False
        Else
            errorProvider.SetError(txtLastName, "")
        End If
        If String.IsNullOrEmpty(txtPhone.Text.Trim()) Then
            errorProvider.SetError(txtPhone, "Phone can not be left blank!")
            res = res And False
        Else
            errorProvider.SetError(txtPhone, "")
        End If
        ' validate email
        Dim r As New Regex("^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$")
        If Not r.IsMatch(txtEmail.Text.Trim()) Then
            errorProvider.SetError(txtEmail, "Email is not valid!")
            res = res And False
        Else
            errorProvider.SetError(txtEmail, "")
        End If
        ' validate phone
        r = New Regex("^[2-9]\d{2}-\d{3}-\d{4}$")
        If Not String.IsNullOrEmpty(txtPhone.Text.Trim()) And Not r.IsMatch(txtPhone.Text.Trim()) Then
            errorProvider.SetError(txtPhone, "Phone is not valid!")
            res = res And False
        Else
            errorProvider.SetError(txtPhone, "")
        End If
        ' validate zip
        r = New Regex("^\d{5,6}")
        If Not String.IsNullOrEmpty(txtZip.Text.Trim()) And Not r.IsMatch(txtZip.Text.Trim()) Then
            errorProvider.SetError(txtZip, "Zip is not valid!")
            res = res And False
        Else
            errorProvider.SetError(txtZip, "")
        End If
        ' validate existing of email
        If CustomerController.loadByEmail(txtEmail.Text.Trim()) IsNot Nothing Then
            errorProvider.SetError(txtEmail, "Email has been already taken. Please choose another.")
            res = res And False
        Else
            errorProvider.SetError(txtEmail, "")
        End If
        Return res
    End Function

    Private Sub CustomerForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim mainForm As MainForm = Me.FindForm()
        mainForm.AcceptButton = Me.btnAdd
        mainForm.CancelButton = Me.btnCancel
        If cust.ID > 0 Then
            mainForm.SetHeader("Update Customer: " & cust.FirstName & " " & cust.LastName)
            txtEmail.Text = cust.Email
            txtPassword.Text = cust.Password
            txtFirstName.Text = cust.FirstName
            txtLastName.Text = cust.LastName
            txtAddress.Text = cust.Address
            txtCity.Text = cust.City
            txtState.Text = cust.State
            txtZip.Text = cust.Zip
            txtPhone.Text = cust.Phone
        Else
            mainForm.SetHeader("Add New Customer")
        End If
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Dim mainForm As MainForm = Me.FindForm()
        If mainForm.isAdmin Then
            mainForm.GoToForm(New CustomerList(), "Customer List")
        Else
            mainForm.GoToForm(New Welcome(), "Welcome")
        End If

    End Sub

    Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
        For Each c As Control In KryptonPanel1.Controls
            If TypeOf c Is KryptonTextBox Then
                Dim txt As KryptonTextBox = c
                txt.Text = ""
            End If
            If TypeOf c Is KryptonRichTextBox Then
                Dim txt As KryptonRichTextBox = c
                txt.Text = ""
            End If
            If TypeOf c Is KryptonComboBox Then
                Dim cbo As KryptonComboBox = c
                cbo.SelectedIndex = 0
            End If
        Next
    End Sub
End Class
